﻿using AutoMapper;
using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys;
using MediatR;
using System.Security.Claims;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.Traceabilitys
{
    /// <summary>
    /// 获取产品信息命令处理
    /// </summary>
    public class AddProductCommandHandlter : IRequestHandler<AddProductCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ProductModel> productRep;
        private readonly IMapper mapper;
        /// <summary>
        /// http上下文
        /// </summary>
        private readonly IHttpContextAccessor httpContextAccessor;

        public AddProductCommandHandlter(IBaseRepository<ProductModel> productRep,IMapper mapper,IHttpContextAccessor httpContextAccessor)
        {
            this.productRep = productRep;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiResult<int>> Handle(AddProductCommand request, CancellationToken cancellationToken)
        {

            //登录人Id
            var UserId = httpContextAccessor?.HttpContext?.User?.FindFirstValue("UserId") ?? "0";

            //先判断是否已经存在溯源信息
            var productname= productRep.GetAll().FirstOrDefault(x=>x.GoodsId==request.GoodsId);

            if(productname!=null)
            {

                return new ApiResult<int>()
                {
                    code = ResultEnumCode.fails,
                    data = 0,
                    message = "该商品已存在溯源信息"

                };

            }

             //添加产品信息
            var product=mapper.Map<ProductModel>(request);
            product.CreateTime = DateTime.Now;
            product.UpdateTime = DateTime.Now;
            product.UpdateUserId = 0;
            product.XuHao = 0;
            product.DelTime= null;
            product.Completeness ="0%";
            product.CreateUserId =Convert.ToInt32(UserId);

            var productsnum=await productRep.AddAsync(product);

            //根据受影响行数判断是否添加成功
            if(productsnum>0)
            {
                return new ApiResult<int>()
                {
                    code = ResultEnumCode.Ok,
                    data = product.ID,
                    message = "添加产品成功"

                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    code = ResultEnumCode.fails,
                    data = productsnum,
                    message = "添加产品失败"

                };

            }
        }
    }
}
